import os.path
import sys
import string
import getopt
import urllib2
import urlparse
from HTMLParser import HTMLParser
from HTMLParser import HTMLParseError
import xml.sax.saxutils
import geturls

helpText = """sitemap_gen.py version 1.0.3 (2008-08-06)

This script crawls a web site from a given starting URL and generates
a Sitemap file in the format that is accepted by Google. The crawler
does not follow links to other web sites.

Command line syntax:

python sitemap_gen.py <options> <starting URL>

Available options:
-h         --help                Print this text and exit

-b <ext>   --block <ext>         Exclude URLs with the given extension;
                                 <ext> must be without the leading dot.
                                 The comparison is case insensitive, so
                                 for example DOC and doc are treated
                                 the same. You can use this option several
                                 times to block several extensions.
                                 
-c <value> --changefreq <value>  Set the change frequency. The given value
                                 is used in all sitemap entries (maybe a
                                 future version of this script will change
                                 that). The allowed values are: always,
                                 hourly, daily, weekly, monthly, yearly,
                                 never.
                                 
-p <prio>  --priority <prio>     Set the priority. The value must be from
                                 the interval between 0.0 and 1.0. The value
                                 will be used in all sitemap entries.
                                 
-m <value> --max-urls <value>    Set the maximum number of URLs to be crawled.
                                 The default value is 1000 and the largest
                                 value that you can set is 50000 (the script
                                 generates only a single sitemap file).
                                 
-o <file>  --output-file <file>  Set the name of the geneated sitemap file.
                                 The default file name is sitemap.xml.

Usage example:
python sitemap_gen.py -b doc -b bmp -o test_sitemap.xml http://www.your-site-name.com/index.html

For more information, visit http://toncar.cz/opensource/sitemap_gen.html

"""

allowedChangefreq = ["always", "hourly", "daily", "weekly", \
                     "monthly", "yearly", "never"]

def getPage(url):
    try:
        f = urllib2.urlopen(url)
        page = ""
        for i in f.readlines():
            page += i
        date = f.info().getdate('Last-Modified')
        if date == None:
            date = (0, 0, 0)
        else:
            date = date[:3]
        f.close()
        return (page, date, f.url)
    except urllib2.URLError, detail:
        print "%s. Skipping..." % (detail)
        return (None, (0,0,0), "")
#end def


def joinUrls(baseUrl, newUrl):
	helpUrl, fragment = urlparse.urldefrag(newUrl)
        return urlparse.urljoin(baseUrl, helpUrl)
#end def


class MyHTMLParser(HTMLParser):

    def __init__(self, pageMap, redirects, baseUrl, maxUrls, blockExtensions):
        HTMLParser.__init__(self)
        self.pageMap = pageMap
	self.redirects = redirects
        self.baseUrl = baseUrl
        self.server = urlparse.urlsplit(baseUrl)[1] # netloc in python 2.5
        self.maxUrls = maxUrls
        self.blockExtensions = blockExtensions
    #end def

    def hasBlockedExtension(self, url):
        p = urlparse.urlparse(url)
        path = p[2].upper() # path attribute
        # In python 2.5, endswith() also accepts a tuple,
        # but let's make it backwards compatible
        for i in self.blockExtensions:
            if path.endswith(i):
                return 1
        return 0
    #end def        

    def handle_starttag(self, tag, attrs):
        if len(self.pageMap) >= self.maxUrls:
            return
        
        if (tag.upper() == "BASE"):
	    if (attrs[0][0].upper() == "HREF"):
		self.baseUrl = joinUrls(self.baseUrl, attrs[0][1])
		print "BASE URL set to", self.baseUrl

	if (tag.upper() == "A"):
            if (attrs[0][0]).upper() == "HREF" \
               and (attrs[0][0]).upper().find('MAILTO:') == -1:
                #print "HREF:", attrs[0][1]
		url = joinUrls(self.baseUrl, attrs[0][1])
                if urlparse.urlsplit(url)[1] <> self.server:
                    return
                if self.hasBlockedExtension(url) or self.redirects.count(url) > 0:
                    return
                if not(self.pageMap.has_key(url)):
                    self.pageMap[url] = ()
                    #print "Adding: ", url
    #end def
#end class


def getUrlToProcess(pageMap):
    for i in pageMap.keys():
        if pageMap[i] == ():
            return i
    return None

def parsePages(startUrl, maxUrls, blockExtensions):
    pageMap = {}
    pageMap[startUrl] = ()
    redirects = []

    while True:
        url = getUrlToProcess(pageMap)
        if url == None:
            break
        print " ", url
        page, date, newUrl = getPage(url)
        if page == None:
            del pageMap[url]
	elif url != newUrl:
	    print "Redirect -> " + newUrl
            del pageMap[url]
	    pageMap[newUrl] = ()
	    redirects.append(url)
        else:
            pageMap[url] = date
            parser = MyHTMLParser(pageMap, redirects, url, maxUrls, blockExtensions)
            try:
                parser.feed(page)
                parser.close()
            except HTMLParseError:
                print "Error parsing %s, skipping." % (url)
    #end while

    return pageMap
#end def


def generateSitemapFile(pageMap, fileName, changefreq="", priority=0.0,baseurl=''):
    
    fw = open(fileName, "wt")
    fw.write('''<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n''')
    for i in pageMap.keys():
        fw.write('<url>\n  <loc>%s</loc>\n' % (xml.sax.saxutils.escape(i)))
        if pageMap[i] not in [(), (0,0,0)]:
            fw.write('  <lastmod>%4d-%02d-%02d</lastmod>\n' % pageMap[i])
        if changefreq <> "":
            fw.write('  <changefreq>%s</changefreq>\n' % (changefreq))
        if priority > 0.0:
            fw.write('  <priority>%1.1f</priority>\n' % (priority))
        fw.write('</url>\n')
    #end for
    
    for urls in geturls.get_list(baseurl):
        fw.write('<url>\n  <loc>%s</loc>\n' % (urls))
        fw.write('</url>\n')
    fw.write('</urlset>')
    fw.close()
#end def
        

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:],\
                "hb:c:m:p:o:", \
                ["help", "block=", "changefreq=", \
                 "max-urls=", "priority=", "output-file="])
    except getopt.GetoptError:
        print helpText
        return

    blockExtensions = []
    changefreq = ""
    priority = 0.0
    fileName = "../bvapp/templates/xml/sitemap.xml"
    maxUrls = 1000
    pageMap = {}

    for opt,arg in opts:
        if opt in ("-h", "--help"):
            print helpText
            return
        elif opt in ("-b", "--block"):
            blockExtensions.append("." + arg.upper())
        elif opt in ("-c", "--changefreq"):
            if arg in allowedChangefreq:
                changefreq = arg
            else:
                print "Allowed changefreq values are:"
                for i in allowedChangefreq:
                    print i
                print
                return
        elif opt in ("-m", "--max-urls"):
            maxUrls = int(arg)
            if (maxUrls < 0) or (maxUrls > 50000):
                print "The maximum number of URLs must be greater than 0 and smaller than 50000"
                return
        elif opt in ("-p", "--priority"):
            priority = float(arg)
            if (priority < 0.0) or (priority > 1.0):
                print "Priority must be between 0.0 and 1.0"
                return
        elif opt in ("-o", "--output-file"):
            fileName = arg
            if fileName in ("", ".", ".."):
                print "Please provide a sensible file name"
                return
        #end if
        
    if len(args) == 0:
        print "You must provide the starting URL.\nTry the -h option for help."
        return

    # Set user agent string
    opener = urllib2.build_opener()
    opener.addheaders = [('User-agent', 'sitemap_gen/1.0')]
    urllib2.install_opener(opener)
    
    # Start processing
    
    no_of_companies=len(geturls.get_list(args[0]))
    print "Crawling the site..."
    
    pageMap = parsePages(args[0], maxUrls, blockExtensions)
    print "Generating sitemap: %d URLs" % (len(pageMap)+no_of_companies)
    generateSitemapFile(pageMap, fileName, changefreq, priority,args[0])
    
    print "Finished."
#end def

if __name__ == '__main__': main()
